package com.trepadora.db;

import java.io.IOException;

import com.fourspaces.couchdb.Database;
import com.fourspaces.couchdb.Document;
import com.fourspaces.couchdb.Session;
import com.trepadora.utils.ChatInterface;

public class CouchDbManager implements ChatInterface {

	private static Session session;
	private static Database db;
	
	public static void main(String[] args){
	
		session = new Session(DB_HOST, DB_PORT);
		
		
		// Create new DB with views if not exist
		try {
			
			db =  session.getDatabase(DB_NAME);
			session.deleteDatabase(DB_NAME);
			
			db = session.createDatabase(DB_NAME);
			
		} catch (Exception e) {
			System.out.println("No DB: " + DB_NAME + " (create)");
			
			db = session.createDatabase(DB_NAME);
		}
		
		System.out.println("Cauch DB name: " + db.getName());
		
		try {
			Document designDoc1 = new Document();
			designDoc1.addView("user", "freeUsers", "function(doc) { if(doc.type=='user' && doc.active==true && doc.busy==false){ emit(doc._id, doc); }}");
			designDoc1.addView("user", "getUserByUsername", "function (doc) {if (doc.type=='user') { emit(doc.username, doc); }}");
			db.saveDocument(designDoc1);
			
			Document designDoc2 = new Document();
			designDoc2.addView("chat", "byRoom", "function(doc) { if(doc.type=='chat'){ emit(doc.room, doc); }}");
			db.saveDocument(designDoc2);
			
			Document designDoc3 = new Document();
			designDoc3.addView("room", "roomByGuest", "function(doc) { if(doc.type=='room' && doc.active==true){ emit(doc.guestId, {hostId: doc.hostId, streamIn: doc.streamIn, streamOut: doc.streamOut}); }}");	
			db.saveDocument(designDoc3);
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
}
